<?php
/* 
 * Copyright (c) 2018-2021   All rights reserved.
 * 
 * 创建时间：2021-05-23 09:55
 *
 * 项目：upload  -  $  - levmodules.php
 *
 * 作者：liwei 
 */

namespace modules\levpays;

use Lev;
use lev\base\Assetsv;
use lev\helpers\UserHelper;
use modules\levpays\table\tradesHelper;
use modules\levpays\table\UsersHelper;

!defined('INLEV') && exit('Access Denied LEV');

class levpaysHelper extends \lev\base\Modulesv
{

    public static $mud = [
        'version' => '1.0.210820',
    ];

    public static function init()
    {
        parent::init(); // TODO: Change the autogenerated stub
        static::loadExtSDK();
        //Assetsv::registerApp(static::$mud['version']);

    }

    public static function assets() {
        return Assetsv::getAppassets('levpays');
    }

    public static function loadExtSDK() {
        Lev::$aliases['@GuzzleHttp'] = __DIR__ . '/sdk/wechatpay/sdk/guzzle';
        Lev::$aliases['@WeChatPay']  = __DIR__ . '/sdk/wechatpay/sdk/wechatpay';
        Lev::$aliases['@Psr']        = __DIR__ . '/sdk/wechatpay/sdk/Psr';
    }

    public static function getOutTradeNo($tradeNo, $pre) {
        return str_replace('.', '_', $pre.'-'.$tradeNo);
    }



    /**
     * 支付成功，更新订单状态，执行成功后续操作
     * @param $res
     * @param $tradeNo
     * @param $pre
     * @param array $outTradeInfo
     * @param array $config
     */
    public static function paySuccess($res, $tradeNo, $pre, $outTradeInfo = [], $config = [])
    {
        if (strpos($res['message'], '单号重复') !== false) {//$res['code'] == 'INVALID_REQUEST'
            $tradeId = tradesHelper::tradeNoToId($tradeNo);
            tradesHelper::update(['tradestatus' => 5], ['id'=>$tradeId]);
        }else if (strpos($res['message'], '已支付') !== false) {//$res['code'] == 'ORDERPAID'

            $tradeId = tradesHelper::tradeNoToId($tradeNo);
            $tradeInfo = tradesHelper::tradeInfo($tradeId);
            if ($tradeInfo && (!$tradeInfo['tradestatus'] || isset($res['_admin_check']))) {
                $paymethod = json_decode($tradeInfo['paymethod']);
                $paymethod[] = $pre;
                $data = [
                    'mchid'       => $config['mchid'],
                    'appid'       => $config['appid'],
                    'paytypeid'   => $config['paytypeid'],
                    'paytime'     => Lev::$app['timestamp'],
                    'tradestatus' => 1,
                    'paymethod'   => json_encode($paymethod),
                ];

                empty($outTradeInfo['openid']) ||
                $uid = UsersHelper::tradeRegUid($outTradeInfo['openid'], $config['openidField']);
                !$tradeInfo['uid'] && !empty($uid) && $data['uid'] = $uid;
                if (!empty($outTradeInfo['_paySuccess'])) {
                    $data['transaction_id'] = $outTradeInfo['transaction_id'];
                    $data['openid']         = $outTradeInfo['openid'];
                    $data['appid']          = $outTradeInfo['appid'];
                    $data['mchid']          = $outTradeInfo['mchid'];
                    $data['paytime']        = is_numeric($outTradeInfo['success_time']) ? $outTradeInfo['success_time'] : strtotime($outTradeInfo['success_time']);
                }
                tradesHelper::update($data, ['id'=>$tradeId]);
                $tradeInfo = $data + $tradeInfo;
                if (Lev::$app['uid'] <1 && $tradeInfo['uid']) {
                    $msg = UserHelper::setLogin(['uid'=>$tradeInfo['uid']]);
                    Lev::setNotices($msg['message']);
                }
                BasePayIden::setPaySuccessByIden($tradeInfo);
            }
        }
    }
}